<template>
    <el-container>
      <div class="header">
        <div class="box1" style="width: 52%; display: flex">
          <el-button style="margin-right: 15px" type="warning" size="medium"
            @click="; (flag = '1'), getProductConfigList()">导入品种单价</el-button>
          <el-button style="margin-right: 15px" type="warning"
            @click="; (flag = '2'), getProductConfigList()">增长比例调整</el-button>
          <el-button style="margin-right: 50px" type="warning"
            @click="; (flag = '3'), getProductConfigList()">库存周转率基础信息表</el-button>
          <el-button type="primary" v-if="flag !== '2'" style="width: 100px" @click="inveDistribution">导入</el-button>
        </div>
  
        <div class="box2">
          <div class="z1" v-if="flag !== '1'">
            <span style="line-height: 50px; font-size: 14px">片区:&nbsp;&nbsp;</span>
            <el-select v-model="search.area" placeholder="全国" style="width: 150px" filterable clearable
              @change="areaChange">
              <el-option v-for="item in areaList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </div>
  
          <div class="z1" v-if="flag !== '2'">
            <span style="line-height: 50px; font-size: 14px">品种:&nbsp;&nbsp;</span>
            <el-select v-model="search.name" placeholder="全部" style="width: 210px" filterable clearable
              @change="specChange">
              <el-option v-for="(item, index) in productSpecList" :key="index" :label="item.name"
                :value="item.name"></el-option>
            </el-select>
          </div>
  
          <el-button v-if="flag == '3'" @click="change1" type="primary" style="width: 100px">批量修改</el-button>
        </div>
      </div>
  
      <el-header style="display: none"></el-header>
  
      <el-main v-if="flag == '1'" class="nopadding">
        <scTable ref="table" border :apiObj="apiObj" :params="params" stripe remoteSort remoteFilter
          @selection-change="selectionChange">
          <el-table-column label="大类" prop="largeCategory" align="center"></el-table-column>
          <el-table-column label="小类" prop="subCategory" align="center"></el-table-column>
          <el-table-column label="简称" prop="name" align="center"></el-table-column>
          <el-table-column label="品种名称" prop="productSpec" align="center"></el-table-column>
          <el-table-column label="每件单价（元）" prop="price" align="center"></el-table-column>
          <el-table-column label="包装数" prop="productNum" align="center"></el-table-column>
          <el-table-column label="最小单价" prop="minPrice" align="center"></el-table-column>
        </scTable>
      </el-main>
  
      <el-main v-if="flag == '2'" class="nopadding">
        <scTable ref="table" :apiObj="apiObj" :params="params" border :cell-style="cellStyle" stripe remoteSort remoteFilter
          hidePagination @selection-change="selectionChange">
          <el-table-column label="区域" prop="area" width="200" align="center"></el-table-column>
          <el-table-column :label='dateYear+"年总任务(一标)"' prop="totalTask" width="200" align="center"></el-table-column>
          <el-table-column label="增长比例占比" prop="proportion" width="200" align="center">
            <template #default="{ row }">
              <template v-if="!row.isEditing">
                <span @dblclick="startEditing(row)" style="display: block; width: 100%">{{ (row.proportion * 100).toFixed(2)
                }}%</span>
              </template>
              <template v-else>
                <el-input-number :controls="false" step="0.01" v-model="row.proportion" @focus="focus = row.proportion"
                  @blur="stopEditing(row)" ref="editInput">
                </el-input-number>
              </template>
            </template>
          </el-table-column>
        </scTable>
      </el-main>
  
      <el-main v-if="flag == '3'" class="nopadding">
        <scTable ref="table" :apiObj="apiObj" border :params="params" stripe remoteSort remoteFilter
          @selection-change="selectionChange">
          <el-table-column type="selection" width="50" align="right"></el-table-column>
          <el-table-column label="品种" prop="productSpec" width="180" align="center"></el-table-column>
          <el-table-column label="区域" prop="area" width="180" align="center"></el-table-column>
          <el-table-column label="周转" prop="stockTurnover" width="180" align="center">
            <template #default="{ row }">
              <template v-if="!row.isEditing">
                <span @dblclick="startEditing(row)" style="display: block; width: 100%">{{ row.stockTurnover }}</span>
              </template>
              <template v-else>
                <!-- 可设置controls添加input加减按钮 -->
                <el-input-number step="0.1" :controls="false" v-model="row.stockTurnover" @blur="stopEditing2(row)"
                  @focus="focus = row.stockTurnover" ref="editInput">
                </el-input-number>
              </template>
            </template>
          </el-table-column>
        </scTable>
      </el-main>
  
      <scFileImport ref="scFileImport" :apiObj="importApi" :maxSize="30" hideButton @success="handleImportSuccess">
      </scFileImport>
  
      <!-- 批量修改弹出框 -->
      <el-dialog v-model="visible2" title="批量修改" :width="500" destroy-on-close @closed="$emit('closed')">
        <p style="margin-bottom: 10px">片区:&nbsp;&nbsp;{{ search.area ? this.search.area : '全部' }}</p>
        <p style="margin-bottom: 10px">品种:&nbsp;&nbsp;{{ search.productSpec ? this.search.productSpec : '全部' }}</p>
        <p style="display: flex; align-items: center">
          周转：<el-input style="width: 150px" v-model="input1" placeholder="请输入修改后的值" />
        </p>
        <template #footer>
          <el-button @click="visible2 = false">取 消</el-button>
          <el-button v-if="mode != 'show'" type="primary" @click="submit()">保 存</el-button>
        </template>
      </el-dialog>
    </el-container>
  </template>
  
  <script>
  export default {
    name: 'basics',
    data() {
      return {
        flag: '1', //控制显示哪个表格
        visible: false,
        visible2: false,
        input1: '',
        apiObj: '',
        focus: '',
        search: {
          area: '', //选择的片区
          name: '', //选择的品种
          productSpec: '',
          type:1
        },
        params:{type:1},
        importApi: this.$API.plan.importOtxProductConfig,
        productSpecList: [], //品种列表
        areaList: [], //片区列表
        selection: '', //选择的表格选择数据
        dateYear: '',//当前年份
      }
    },
    watch: {
      flag() {
        // console.log('变化了', this.flag)
        if (this.flag == '1') {
          this.importApi = this.$API.plan.importOtxProductConfig
        } else if (this.flag == '3') {
          this.importApi = this.$API.plan.importOtxTurnover
        }
      }
    },
    created() {
      this.getProductConfigList()
      // this.getProductConfig()
      this.getProductSpec() //获取品种
      this.getArea() //获取片区
      this.getDate()//获取当前年份
    },
    methods: {
      // 获取当前年份
      getDate() {
        const currentDate = new Date();
        // 获取当前年份
        this.dateYear=currentDate.getFullYear();
      },
      // //获取产品列表
      async getProductConfigList() {
        if (this.flag == '1') {
          this.apiObj = this.$API.plan.productConfigList2
        } else if (this.flag == '2') {
          this.apiObj = this.$API.plan.growthRateList
        } else {
          this.apiObj = this.$API.plan.stockTurnoverList
        }
      },
      //获取品种列表
      async getProductSpec() {
        let res = await this.$API.plan.productList2.get()
        this.productSpecList = res.data
      },
      //获取片区列表
      async getArea() {
        let res = await this.$API.plan.areas2.get()
        res.data.forEach((item) => {
            this.areaList.push(item)
        })
      },
  
      // 品种发生变化触发
      specChange(value) {
        if (!value) {
          this.search.name = ''
          this.upsearch()
        }
        this.search.name = value
        this.search.productSpec = value
        this.$nextTick(() => {
          this.$refs.table.upData(this.search)
        })
      },
      // 片区发生改变
      areaChange(value) {
        // console.log(value);
        if (!value) {
          this.search.area = ''
          this.upsearch()
        } else {
          let obj = this.areaList.find((item) => item=== value)
          this.search.area = obj
          this.$nextTick(() => {
            this.$refs.table.upData(this.search)
          })
        }
      },
      //查询功能
      upsearch() {
        this.search.month = Number(this.planCode)
        this.$refs.table.upData(this.search)
      },
  
      //表格选择后回调事件
      selectionChange(selection) {
        this.selection = selection
        // console.log(selection)
      },
  
      //导入品种单价
      inveDistribution() {
        this.$refs.scFileImport.open()
      },
  
      // 导入成功后
      handleImportSuccess(res, close) {
        // console.log('qqqqq',res);
        if (!res?.data) {
          return
        }
        this.$message.success(`已成功导入 ${res.data.insertNum} 条数据，更新 ${res.data.updateNum} 行数据`)
        close()
        this.$refs.table.upData()
      },
  
      // 库存周转导入成功后
      handleImportSuccess2(res, close) {
        if (!res?.data) {
          return
        }
        this.$message.success(`已成功导入 ${res.data.insertNum} 条数据，更新 ${res.data.updateNum} 行数据`)
        close()
        this.$refs.table.upData()
      },
  
      startEditing(row) {
        row.isEditing = true
        this.$nextTick(() => {
          this.$refs.editInput.$refs.input.focus()
        })
      },
      async stopEditing(row) {
        row.isEditing = false
        console.log(this.focus)
        if (this.focus == row.proportion) {
          return
        }
        // console.log('双击数据', row)
        // console.log('输入框数据', row.proportion)
        let res = await this.$API.plan.editGrowthRate.post({
          data: {
            id: row.id,
            proportion: row.proportion,
            type:1
          }
        })
        if (res.code == '0') {
          this.$message.success('修改成功')
        }
        this.$refs.table.upData()
  
        // console.log(res)
      },
      // 是否显示批量修改弹窗
      change1() {
        // this.visible2 = true
        if (this.selection.length == 0) {
          this.$message.warning('请先选择要修改的品种')
        } else {
          this.visible2 = true
        }
      },
      // 批量修改保存功能
      async submit() {
        // console.log(this.input1)
        // console.log(this.selection)
        let selectData = []
        this.selection.forEach((e) => {
          selectData.push({
            id: e.id,
            stockTurnover: this.input1,
            type:1
          })
        })
        console.log(selectData)
        let res = await this.$API.plan.batchEditStockTurnover.post({
          data: [...selectData]
        })
        if (res.code == '0') {
          this.$message.success('修改成功')
        }
        this.$refs.table.upData()
        this.visible2 = false
        this.input1 = ''
      },
      // 库存周转单独修改功能
      startEditing2(row) {
        row.isEditing = true
        this.$nextTick(() => {
          this.$refs.editInput.$refs.input.focus()
        })
      },
      async stopEditing2(row) {
        row.isEditing = false
        if (this.focus == row.stockTurnover) {
          return
        }
        let res = await this.$API.plan.editStockTurnover.post({
          data: {
            id: row.id,
            stockTurnover: row.stockTurnover,
            type:1
          }
        })
        if (res.code == '0') {
          this.$message.success('修改成功')
        }
        this.$refs.table.upData()
      }
    }
  }
  </script>
  
  <style scoped lang='scss'>
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 0 15px;
  }
  
  .header .box2 {
    width: 48%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  
  .header .box2 .z1 {
    display: flex;
    align-items: center;
  }
  </style>